// MarkupParser.cpp : Implementation of CMarkupParser

#include "stdafx.h"
#include "MarkupParser.h"
#include ".\markupparser.h"


// CMarkupParser


STDMETHODIMP CMarkupParser::Parse(BSTR bstrText, IParserCallback* pCallback)
{
	if (pCallback == NULL)
		return E_POINTER;
	// Convert the BSTR to a standard C string and parse it
	COLE2T pszText(bstrText);

	// mask the <%% and %%> characters so that the parser won't recognize it
	//string text = MaskText(pszText.m_psz);
	CAtlString szText = pszText;
	if (szText.Find("<%%") > 0)
		szText.Replace("<%%","\253");
	if (szText.Find("%%>") > 0)
		szText.Replace("%%>","\254");

	///codesmithparser parser;

	pCallback->OnBeginParse();
	
	vector<Token> v;
	bool bResult = false;
	try
	{
		bResult = codesmithparser::parsetext(szText, v);
		//::parse(szText, v);
	}
	catch(parser_exception ex)
	{
		CAtlString szText;
		szText.Format("Error: %s\nLine: %d\nPosition: %d", ex.msg, ex.line, ex.column);
#ifdef DEBUG
		
		DebugConsole* Console = DebugConsole::Instance();

		Console->Write(szText.GetBuffer());
		Console->Write("\n");
#endif
		Error(szText);
	}
	if (!bResult)
	{
#ifdef DEBUG
		DebugConsole* Console = DebugConsole::Instance();
		Console->Write("Parsing Failed!\n");
#endif
		Error("Parsing Failed!");
	}
	
	// then go through the markup text and start calling back
	for(vector<Token>::iterator iter = v.begin(); iter != v.end(); iter++)
	{
		CAtlString pszCurrent = iter->text.c_str();
		if (iter->markuptype == LiteralText)
		{
			pszCurrent.Replace("\253", "<%");
			pszCurrent.Replace("\254", "%>");
		}
		CComBSTR bstrMarkupText(pszCurrent);
		pCallback->OnMarkupText(iter->markuptype, bstrMarkupText);
	}
	pCallback->OnParseComplete();
	
	return S_OK;
}
